package io.gitee.zhangbinhub.admin.service

import io.gitee.zhangbinhub.admin.base.OauthBaseService
import io.gitee.zhangbinhub.admin.entity.MyProcessInstance
import io.gitee.zhangbinhub.admin.repo.MyProcessInstanceRepository
import io.gitee.zhangbinhub.admin.repo.UserRepository
import io.gitee.zhangbinhub.admin.vo.ProcessInstanceVo
import org.dromara.warm.flow.core.entity.Instance
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
@Transactional(readOnly = true)
class MyProcessInstanceService(
    userRepository: UserRepository,
    private val myProcessInstanceRepository: MyProcessInstanceRepository,
) : OauthBaseService(userRepository) {
    @Transactional
    fun addMyProcessInstance(userId: String, instance: Instance, processInstanceVo: ProcessInstanceVo) {
        myProcessInstanceRepository.findByUserIdAndProcessInstanceId(userId, instance.id).let {
            if (it.isEmpty) {
                myProcessInstanceRepository.save(
                    MyProcessInstance(
                        processInstanceId = instance.id,
                        processDefinitionKey = processInstanceVo.processDefinitionKey!!,
                        businessKey = instance.businessId,
                        startUserId = processInstanceVo.startUser?.id,
                        userId = userId,
                        startTime = processInstanceVo.startTime
                    )
                )
            }
        }
    }
}